import django_filters
from django.db.models import Q

from common.models import Agent, HouseInfo


class AgentFilterSet(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_expr='startswith')
    minstar = django_filters.NumberFilter(field_name='servstar', lookup_expr='gte')
    maxstar = django_filters.NumberFilter(field_name='servstar', lookup_expr='lte')

    class Meta:
        model = Agent
        fields = ('name', 'minstar', 'maxstar')


class HouseInfoFilterSet(django_filters.FilterSet):
    title = django_filters.CharFilter(lookup_expr='contains')
    minprice = django_filters.NumberFilter(field_name='price', lookup_expr='gte')
    maxprice = django_filters.NumberFilter(field_name='price', lookup_expr='lte')
    district = django_filters.NumberFilter(method='filter_by_district')

    @staticmethod
    def filter_by_district(queryset, name, value):
        return queryset.filter(Q(district_level2=value) |
                               Q(district_level3=value))

    class Meta:
        model = HouseInfo
        fields = ('title', 'minprice', 'maxprice', 'type', 'district')
